const {src, dest, series, parallel, watch}  = require("gulp")
const less = require("gulp-less")
const autoprefixer = require("gulp-autoprefixer")
const cleanCSS = require("gulp-clean-css")
const rename = require("gulp-rename")
const uglify = require("gulp-uglify")
const miniHtml = require("gulp-htmlmin")
const imgmin = require("gulp-imagemin")
const del = require("del")
const browserSync = require("browser-sync")
const bs = browserSync.create()

const style = () => {
  return src("./css/index.css", {base: './'})
  .pipe(less())
  .pipe(autoprefixer())
  .pipe(cleanCSS())
  .pipe(rename({
    extname: '.css'
  }))
  .pipe(dest("./dist"));
}

const javaScript = () => {
  return src("./js/index.js", {base: './'})
  .pipe(uglify())
  .pipe(rename({
    extname: '.js'
  }))
  .pipe(dest("./dist"));
}

const native = () => {
  return src("./js/template-native.js", {base: './'})
  .pipe(dest("./dist"));
}

const jquery = () => {
  return src("./js/jquery-1.12.4.min.js", {base: './'})
  .pipe(dest("./dist"));
}

const htmlmin = () => {
  return src("./index.html", {base: './'})
  .pipe(miniHtml({
     collapseWhitespace: true ,
     minifyCSS: true,
     minifyJS: true,
     minifyURLs: true
  }))
  .pipe(dest("./dist"));
}


const imagemin = () => {
  return src("./img/*", {base: './'})
  // .pipe(imgmin(
  //   [
  //     imagemin.mozjpeg({quality: 75, progressive: true}),
  //   ]
  // ))
  .pipe(dest("./dist"));
}

const clean = () => {
  return del(["dist"]);
}

const server = () => {
  // watch 被监视的文件，执行对应的任务
  watch('./index.html', htmlmin)
  watch('./css/*.css', style)
  watch('./js/*.js', javaScript)
  watch('./img/**', imgmin)

  bs.init({
    notify: false,  //禁用浏览器右上角的 browserSync
    files: 'dist/**',  // 监视dist下文件的变化
    server: {
      baseDir: './dist', //指定服务启动的目录
      routes: {
        "/js": "dist/js",
        "img": 'dist/img'
      }
    }
  })
}

const build = parallel(style, javaScript, htmlmin, native ,jquery)
const dev =  series(clean, build, server)

module.exports = {
  // style, javaScript, htmlmin, imagemin, clean,
   build, dev
}